package cn.boge.hrm.service.impl;

import cn.boge.hrm.dto.SMSCodeDTO;
import cn.boge.hrm.dto.SendSmsCodeDTO;
import cn.boge.hrm.exception.Assert;
import cn.boge.hrm.exception.BusinessException;
import cn.boge.hrm.service.IVerifycodeService;
import cn.boge.hrm.util.StrUtils;
import cn.boge.hrm.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    public String imageCode(String key) {
        //参数校验
        Assert.assertNotEmpty(key,"无效请求");
        //工具类生成随机字符串
        String code = StrUtils.getComplexRandomString(4);
        //把图片验证码存储到redis中 方便之后做校验    传前端给的key
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        try {
            //生成验证码的图片并转换为
            return VerifyCodeUtils.VerifyCode(130,35,code);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void sendSmsCode(SendSmsCodeDTO dto) {
        //参数校验在dto里字段上面打标签   手机号 图形验证码 key
        String imageCode = dto.getImageCode();
        String imageCodeKey = dto.getImageCodeKey();
        String mobile = dto.getMobile();
        //校验验证码是否正确 在redis中查询
        String imageCodeformredis = (String)redisTemplate.opsForValue().get(imageCodeKey);
        Assert.assertNotEmpty(imageCodeformredis,"无效的验证码或验证码过期了");
        //equalsIgnoreCase 忽略大小写比较
        if (!imageCodeformredis.equalsIgnoreCase(imageCode))
            throw new BusinessException("图片验证码错了！！！");
        //先获取上一次的发送记录
        String codekey = "sms:"+mobile;
        SMSCodeDTO smsCodeDTO = (SMSCodeDTO)redisTemplate.opsForValue().get(codekey);
        String smscode = null;
        Date date = new Date();
        if (smsCodeDTO!=null){
            //上一次的验证码还在
            //判断时间是否超过60s
            if (date.getTime()-smsCodeDTO.getSendTime()/1000>60){
                throw new BusinessException("你能不能慢一点点？？？？");
            }
            smscode = smsCodeDTO.getSmsCode();
        }else {
            //验证码不存在 生成验证码
            smscode = StrUtils.getRandomString(6);
        }
        //将验证码存储在redis中 并设置过期时间
        SMSCodeDTO codeDTO = new SMSCodeDTO(smscode, date.getTime());
        redisTemplate.opsForValue().set(codekey,codeDTO,6,TimeUnit.MINUTES);
        //调用网关发送验证码
        log.info("发送的短信验证码：{}",smscode);
        //写一个记录  查看短信验证码发送记录 可以写一些 ip 时间 手机号 验证码等数据


    }
}
